package com.link2room.aeriabots.thread.task;

import com.link2room.aeriabots.thread.TaskResult;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.SpringUtil;
import com.link2room.aeriabots.entity.WxMemberInfo;
import com.tencent.client.ComponentClient;
import com.tencent.common.Configure;
import com.tencent.protocol.component.user_info_protocol.UserInfoReqData;
import com.tencent.protocol.component.user_info_protocol.UserInfoResData;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by LN on 2016/9/7.
 */
public class WxUserInfoSaveTask implements Callable<TaskResult> {
    private ICommonService commonService;


    private String scope;
    private String openid;
    private String accessToken;
    private String lhotelCode;
    private String lhotelGroupCode;
    public WxUserInfoSaveTask(String lhotelGroupCode,String lhotelCode, String scope , String openid, String  accessToken) {
        this.scope = scope;
        this.openid = openid;
        this.accessToken =accessToken;
        this.lhotelCode = lhotelCode;
        this.lhotelGroupCode = lhotelGroupCode;
        commonService =  (ICommonService) SpringUtil.getBean("commonServiceSupport");
    }
    @Override
    public TaskResult call() throws Exception {
        TaskResult result = new TaskResult();
        try{
            WxMemberInfo wxMemberInfo = new WxMemberInfo();
            wxMemberInfo.setOpenid(openid);
            WxMemberInfo wxMemberInfoRes = commonService.findOneEQ(WxMemberInfo.class, wxMemberInfo);
            if(wxMemberInfoRes != null){
                wxMemberInfo = wxMemberInfoRes;
            }
            UserInfoResData res = null;

            String unionid = "";
            if("snsapi_userinfo".equals(scope)){
                ComponentClient client = new ComponentClient(new Configure());
                UserInfoReqData req = new UserInfoReqData(accessToken,openid);
                res = client.requestUserInfo(req);
                unionid = res.getUnionid();
                wxMemberInfo.setUnionid(unionid);
                wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
                wxMemberInfo.setCity(res.getCity());
                wxMemberInfo.setCountry(res.getCountry());
                wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
                wxMemberInfo.setProvince(res.getProvince());
                wxMemberInfo.setSex(res.getSex().toString());
                wxMemberInfo.setUnionid(unionid);
                wxMemberInfo.setNickname(EmojiFilter.filterEmoji(res.getNickname()));
                wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
                wxMemberInfo.setCity(res.getCity());
                wxMemberInfo.setCountry(res.getCountry());
                wxMemberInfo.setHeadimgurl(res.getHeadimgurl());
                wxMemberInfo.setProvince(res.getProvince());
                wxMemberInfo.setSex(res.getSex().toString());
                wxMemberInfo.setUnionid(unionid);
            }
            wxMemberInfo.setLhotelCode(lhotelCode);
            wxMemberInfo.setLhotelGroupCode(lhotelGroupCode);
            List<WxMemberInfo> wiList = new ArrayList<>();
            wiList.add(wxMemberInfo);
            commonService.saveOrMergeList(wiList);
            result.setResultCode(TaskResult.SUCCESS);
        }catch (Exception e){
            result.setResultCode(TaskResult.ERROR);
            result.setResultMessage("Task had Exception:"+e.getMessage());
            result.setException(e);
        }
        return result;
    }
    /**
     * 过滤表情
     */
    public static class EmojiFilter{
        /*
   * 将字符转为Unicode码表示
   */
        public static String string2unicode(String str){
            str = (str == null ? "" : str);
            String tmp;
            StringBuffer sb = new StringBuffer(1000);
            char c;
            int i, j;
            sb.setLength(0);
            for (i = 0; i < str.length(); i++)
            {
                c = str.charAt(i);
                sb.append("\\u");
                j = (c >>>8); //取出高8位
                tmp = Integer.toHexString(j);
                if (tmp.length() == 1)
                    sb.append("0");
                sb.append(tmp);
                j = (c & 0xFF); //取出低8位
                tmp = Integer.toHexString(j);
                if (tmp.length() == 1)
                    sb.append("0");
                sb.append(tmp);

            }
            return (new String(sb));
        }

        private  static boolean notisEmojiCharacter( char codePoint ){
            return (codePoint == 0x0) ||
                    (codePoint == 0x9) ||
                    (codePoint == 0xA) ||
                    (codePoint == 0xD) ||
                    ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                    ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                    ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
        }

        public static boolean containsEmoji(String source) {
            int len = source.length();
            for (int i = 0; i < len; i++) {
                char codePoint = source.charAt(i);
                if (!notisEmojiCharacter(codePoint)) {
                    //判断确认有表情字符
                    return true;
                }
            }
            return false;
        }
        /**
         * 过滤emoji 或者 其他非文字类型的字符
         * @param source  需要过滤的字符串
         * @return
         */
        public static String filterEmoji(String source) {
            if (!containsEmoji(source)) {
                return source;//如果不包含，直接返回
            }

            StringBuilder buf = null;//该buf保存非emoji的字符
            int len = source.length();
            for (int i = 0; i < len; i++) {
                char codePoint = source.charAt(i);
                if (notisEmojiCharacter(codePoint)) {
                    if (buf == null) {
                        buf = new StringBuilder(source.length());
                    }
                    buf.append(codePoint);
                }
            }

            if (buf == null) {
                return "";//如果没有找到非emoji的字符，则返回无内容的字符串
            } else {
                if (buf.length() == len) {
                    buf = null;
                    return source;
                } else {
                    return buf.toString();
                }
            }
        }
    }
}
